<?php

namespace App\Http\Controllers;

use App\Common\Constant\Params;
use App\Events\OrderEmployed;
use App\Models\MerchantTradeLog;
use App\Models\Order;
use App\Services\Factory\PaymentFactory;
use App\Services\IPayService;
use App\Services\IWeinxinQyService;
use Illuminate\Http\Request;
use Log;

class CallbackController extends BaseController
{
    //
    function __invoke()
    {
        return 'callback';
    }

    /**
     * 支付宝支付，通知回调
     * @param Request $request
     */
    public function aliPay(Request $request,IPayService $payService)
    {
        Log::info('alipay callback',['HTTP_RAW_POST_DATA'=>file_get_contents('php://input')]);
        $payer = PaymentFactory::factory(Params::PAY_METHOD_ALIPAY);
        list($trade_number,$payment_gate_number,$attach) = $payer->notify();
        Log::info('alipay notify result',[$trade_number,$payment_gate_number,$attach]);

        $trade_log = MerchantTradeLog::where('trade_number',$trade_number)->first();
        if (!$trade_log){
            throw new \Exception('miss trade log');
        }
        $order = Order::find($trade_log->order_number_list);
        if (!$order){
            throw new \Exception('miss $order');
        }

        $ret = $trade_log->update([
                'alipay_no' => $payment_gate_number
            ]) && $order->each(function($item,$key){
                return $item->update([
                        'pay_time' => time()
                    ]);
            });
        return ($ret ? 'success' : 'fail');
    }
}
